package cn.geminis.data.jpa.graphql;

import cn.geminis.data.jpa.GeminiRepository;
import cn.geminis.data.jpa.graphql.utils.JpaEntityTypeUtils;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;

import javax.persistence.EntityManager;
import java.util.stream.Collectors;

/**
 * @author puddi
 */
public class GraphQLSchemaBuilder extends GraphQLSchema.Builder {

    private EntityManager entityManager;
    private GeminiRepository geminiRepository;

    public GraphQLSchemaBuilder(EntityManager entityManager, GeminiRepository geminiRepository) {
        this.entityManager = entityManager;
        this.geminiRepository = geminiRepository;

        super.query(createQueryType());
    }

    private GraphQLObjectType createQueryType() {
        var entities = entityManager.getMetamodel().getEntities();

        var queryType = GraphQLObjectType.newObject().name("JPAQueryType");
        queryType.fields(entities.stream()
                .map(entity -> JpaEntityTypeUtils.getEntityField(entityManager, geminiRepository, entity))
                .collect(Collectors.toList())
        );

        return queryType.build();
    }
}
